#pragma once
#include<iostream>
#include<fstream>
#include<unordered_map>
#include"log.hpp"
#include"InetAddr.hpp"
#include"InetAddr.hpp"


using namespace LogModule;

const std::string defaultdict="./dictionary.txt";
const std::string sep=":";



class Dict
{

    public:
    Dict(const std::string & path=defaultdict)
    :_dict_path(path)
    {

    }


    ~Dict()
    {

    }


    bool LoadDict()
    {
        //打开文件
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::DEBUG)<<"打开字典："<<_dict_path<<"错误";
            return false;
        }
        std::string line;
        while(getline(in,line))
        {
            auto pos=line.find(sep);
            if(pos==std::string::npos)
            {
                LOG(LogLevel::WARNING)<<"解析："<<line<<"失败";
                continue;
            }
            std::string english=line.substr(0,pos);
            std::string chinese=line.substr(pos+sep.size());
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING)<<"没有有效内容:"<<line;
                continue;
            }
            _dict.insert({english,chinese});
            LOG(LogLevel::DEBUG)<<"加载:"<<line;
        }
        in.close();
        return true;
    }


    std::string Translate(const std::string &word,InetAddr& peer)
    {
         auto find=_dict.find(word);
        
         if(find==_dict.end())
         {
            LOG(LogLevel::INFO)<<"用户:"<<peer.StringAddr()<<",端口:"<<peer.Port()<<"翻译"<<"["<<word<<":"<<"None]";
            return "None"; 
         }
          LOG(LogLevel::INFO)<<"用户:"<<peer.StringAddr()<<",端口:"<<peer.Port()<<"翻译"<<"["<<find->first<<":"<<find->second<<"]";

         return find->second;

    }



    private:
    std::string _dict_path;
    std::unordered_map<std::string,std::string> _dict;




};
